<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use App\Models\AdminPermission;
use Illuminate\Support\Facades\DB;

class AdminUser
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            if ($request->path() == '/login') {
                return redirect('/admin');
            }
        } else {
            if ($request->path() != '/login') {
                return redirect('/login');
            }
        }

        // 权限方法调用
        $check = $this->userPermissionCheck($request);

        if ($check !== true) {
            return $check;
        }
        return $next($request);
    }

    // 权限判断方法
    private function userPermissionCheck($request)
    {
        $method = $request->method();

        $url = $request->route()->uri();
        $url = '/'.$url;
        // $url = substr($url, 1);
//        DB::connection()->enableQueryLog();
        $data = AdminPermission::join('admin_role_permission as role_permission', 'admin_permission.id', '=', 'role_permission.permission_id')
            ->join('admin_user_role as user_role', 'role_permission.role_id', '=', 'user_role.role_id')
            ->where('user_role.user_id', '=', Auth::user()->id)
            ->where('admin_permission.http_method', 'like', '%'.$method.'%')
            ->where('admin_permission.http_path', '=', $url)
            ->select('admin_permission.id')
            ->first();
//        print_R(DB::getQueryLog());exit;
        if (!isset($data->id)) {
            return $this->ReturnError();
        }
        return true;
    }

    // 错误返回方法
    private function ReturnError()
    {
        // php 判断是否为 ajax 请求
        if(isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest"){
            // ajax 请求的处理方式
            //需要返回的数据
            $result = [
                "code"      => 405,
                "success"   => false,
                "msg"       => '未授权',
                "data"      => '未授权',
            ];
            return response()->json($result);
        }else{
            // 正常请求的处理方式
            $result = [
                "code"      => 403,
                "success"   => false,
                "msg"       => '未授权',
                "data"      => '未授权',
            ];
            return response()->json($result);
        }
    }
}
